package com.sinog.front.easyexcel;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.ConvertHttpToMap;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.config.log.Log;
import com.sinog.front.easyexcel.listensr.ExcelDownloadListener;
import com.sinog.front.feign.biz.BaseInfoblService;
import com.sinog.front.feign.biz.FtpUtilService;
import com.sinog.front.service.user.UserFacade;
import com.sinog.front.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @desc 预安置人员数据录入，方式3：excel批量导入
 * @author lzq
 * @date 2022-03-20 9:41 上午
 */
@Slf4j
@RestController
public class ExcelImportController {

    @Resource
    private BaseInfoblService baseInfoblService;
    @Resource
    private FtpUtilService ftpUtilService;
    @Resource
    private UserFacade userFacade;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 导入excel并解析批量导入模版
     * @param file file
     * @return Result
     */
    @Log(type = "查询", value = "导入excel并解析批量导入模版")
    @RequestMapping(value = "/azbj/import/scanfile", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public Result scanFilesWithNoRecursion(@RequestParam(value = "file", required = false) MultipartFile file) {
        InputStream inputStream = null;
        List<Integer> nums = new ArrayList<>();
        try {
            byte[] byteArr = file.getBytes();
            inputStream = new ByteArrayInputStream(byteArr);
            // 解析每行结果在listener中处理
            String uuids;
            StringBuilder prinum = new StringBuilder(16);
            SimpleDateFormat simformat = new SimpleDateFormat("yyyyMMdd");
            String dateformat = simformat.format(new Date());
            long uuid1 = stringRedisTemplate.opsForHash().increment("uuid",userFacade.getAuthentication()
                                                                                     .getDepartid() + dateformat,1L);
            String seqCodeEnd = Long.toString(uuid1);
            // 更改服刑人员编号生成规则
            while(Constants.Number.NUM_FOUR > seqCodeEnd.length()) {
                seqCodeEnd = new StringBuilder(16).append(Constants.NumberStr.NUM_STR_ZERO).append(seqCodeEnd).toString();
            }
            prinum.append(dateformat).append(seqCodeEnd);
            uuids = prinum.toString();
            if(Constants.RoleId.ROLE_ID_JY.equals(userFacade.getAuthentication().getRoleid())) {
                uuids = "JY-" + uuids;
            } else if(Constants.RoleId.ROLE_ID_KSS.equals(userFacade.getAuthentication().getRoleid())) {
                uuids = "KSS-" + uuids;
            } else if(Constants.RoleId.ROLE_ID_SJZX.equals(userFacade.getAuthentication().getRoleid())) {
                uuids = "SJZX-" + uuids;
            }
            ExcelDownloadListener listener = new ExcelDownloadListener(uuids);
            Sheet sheet = new Sheet(1,1,ImportInfo.class);
            //开始读取
            new ExcelReader(inputStream,ExcelTypeEnum.XLSX,null,listener).read(sheet);
            //获取监听器中结果
            Integer total = listener.getTotal();
            Integer success = listener.getSuccess();
            Integer fail = listener.getFail();
            log.error("..............................总数:{}",total);
            log.error("..............................成功:{}",success);
            log.error("..............................失败:{}",fail);
            nums.add(total);
            nums.add(success);
            nums.add(fail);
        } catch(ExcelAnalysisException e) {
            log.error("发生异常:",e);
            Result.failure(ReturnCode.JIEXI_FAIL);
        } catch(Exception e) {
            log.error("发生异常:",e);
            Result.failure(ReturnCode.ALL_FAILURE);
        } finally {
            try {
                if(null != inputStream) {
                    inputStream.close();
                }
            } catch(IOException e) {
                log.error("发生异常:",e);
            }
        }
        return Result.success(nums);
    }

    /**
     * 下载文件 /报告生成文件下载、下载支持文件(视频、pdf)、
     * @param request request
     * @param resp resp
     * @param type type
     */
    @Log(type = "查询", value = "下载excel批量导入数据库模版")
    @RequestMapping("/azbj/import/template/downloadFiles")
    public void downloadFile(HttpServletRequest request,HttpServletResponse resp,String type) {
        PrintWriter writer = null;
        String fileUrl;
        String fileName;
        if(Constants.NumberStr.NUM_STR_ONE.equals(type)) {
            fileUrl = "excel-template-check.xlsx";
            if(Constants.OrgLevel.LEVEL_SJZX.equals(userFacade.getAuthentication().getLevel())){
                fileUrl = "excel-template-check-sj.xlsx";
            } else if(Constants.OrgLevel.LEVEL_KSS.equals(userFacade.getAuthentication().getLevel())) {
                fileUrl = "excel-template-check-kss.xlsx";
            }
            fileName = "批量导入预安置人员模版2.0.xlsx";
        } else if(Constants.NumberStr.NUM_STR_TWO.equals(type)) {
            fileUrl = "excel-template-nocheck.xlsx";
            fileName = "批量导入预安置人员模版2.0-无校验版.xlsx";
        } else {
            return;
        }
        boolean fileUrlBoolean = StringUtils.isBlank(fileUrl) || fileUrl.contains("/") || !fileUrl.contains(".");
        boolean fileNameBoolean = StringUtils.isBlank(fileName) || fileName.contains("/") || !fileName.contains(".");
        try {
            if(fileUrlBoolean || fileNameBoolean) {
                try {
                    resp.setContentType("text/html; charset=utf-8");
                    writer = resp.getWriter();
                    writer.println("<script type=\"text/javascript\">alert('请求不合法');window.history.back(-1);</script>");
                    writer.flush();
                    return;
                } catch(IOException e) {
                    log.error("请求不合法:{}",e.getMessage());
                    return;
                } finally {
                    if(null != writer) {
                        writer.close();
                    }
                }
            }
            String path = FileUtil.getFileTemplatePath();
            ftpUtilService.downLoadFromFtp(path + fileUrl,fileName);
            FileUtil.downloadFile(request,resp,path + fileUrl,fileName);
        } catch(Exception e) {
            try {
                resp.setContentType("text/html; charset=utf-8");
                writer = resp.getWriter();
                writer.println("<script type=\"text/javascript\">alert('文件不存在');window.history.back(-1);</script>");
                writer.flush();
            } catch(IOException ex) {
                log.error("下载发生异常:{}",e.getMessage());
            } finally {
                if(null != writer) {
                    writer.close();
                }
            }
        }
    }

    /**
     * 开始保存数据到真实数据库
     * @param request request
     * @param resp resp
     * @return Result
     */
    @Log(type = "更新", value = "保存excel导入的解析正确数据到真实数据库")
    @RequestMapping("/azbj/import/baseinfo/saveExcelImportData")
    public Result saveExcelImportData(HttpServletRequest request,HttpServletResponse resp) {
        log.error("........................开始保存数据到真实数据库........................");
        UserDTO authentication = userFacade.getAuthentication();
        String departid = authentication.getDepartid();
        return baseInfoblService.selectMainExcels(departid,authentication);
    }

    /**
     * 檢查主表excel緩存表是否有數據
     * @param request request
     * @param resp resp
     * @return Result
     */
    @RequestMapping("/azbj/import/baseinfo/checkMainExcelImportData")
    public Result checkMainExcelImportData(HttpServletRequest request,HttpServletResponse resp) {
        UserDTO authentication = userFacade.getAuthentication();
        String departid = authentication.getDepartid();
        return baseInfoblService.checkMainExcelImportData(departid);
    }

    /**
     * 日期级联查询批次号
     * @param request request
     * @return List<Map<String,String>>
     */
    @RequestMapping("/azbj/import/search/code/selectUuidByDate")
    public List<Map<String,String>> toSearchCodeNativeList(HttpServletRequest request) {
        Map<String,Object> searchMap = ConvertHttpToMap.getParameterMap(request);
        String date = (String)searchMap.get("date");
        return baseInfoblService.getUuidList(date);
    }
}